package com.ny.service.impl;

import com.ny.entity.User;
import com.ny.mapper.UserMapper;
import com.ny.service.EmailService;
import com.ny.service.UserService;
import com.ny.until.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EmailService emailService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public List<User> findAll() {
        System.out.println(userMapper.findAll());
        return userMapper.findAll();
    }

    @Override
    public User findUser(String username, String password) {
        return  userMapper.findUser(username,password);
    }

    @Override
    public boolean register(User user) {
        user.setPassword(PasswordUtil.md5(user.getPassword()));
        // 修复逻辑错误：只有添加成功才返回true
        return userMapper.addUser(user) > 0;
    }

    @Override
    public int findUserByEmail(String email) {
        return userMapper.findUserByEmail(email);
    }

    @Override
    public int updateUser(String email, String password) {
        // 密码加密
        return userMapper.updateUser(email, PasswordUtil.md5(password));
    }

    @Override
    public void sendEmail(String email) {
        // 生成验证码
        String code = emailService.generateCode();
        // 存储验证码到redis
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        ops.set(email, code, 10, TimeUnit.MINUTES); // 存储10分钟
        // 发送验证码到邮箱
        emailService.sendEmail(email, code);
    }

    @Override
    public boolean findEmail(String email, String code) {
        // 从redis获取验证码并判断
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String redisCode = ops.get(email);
        return redisCode != null && redisCode.equals(code);
    }
}
